﻿using System;
using Microsoft.JScript.Vsa;
using System.Text.RegularExpressions;

namespace Helper
{
    public static class ScriptHelper
    {
        // Added by jetic@sina.com 2008-9-26
        public static string GetAccCode_Re(string content)
        {
            string Pattern = "";
            string accCode = "";
            string script = "";
            string script_tmp2 = "";
            string var_values = "";

            //得到所有script段
            Pattern = @"<script.*?>(?<x>.*?)</script>";
            MatchCollection scripts = Regex.Matches(content, Pattern, RegexOptions.Singleline);

            //查找符合要求的script段
            Pattern = @"function\s*?acc";
            foreach (Match script_tmp in scripts)
            {
                if (Regex.IsMatch(script_tmp.Groups["x"].ToString(), Pattern, RegexOptions.Singleline))
                {
                    script = script_tmp.Groups["x"].ToString();
                }
            }

            if (script.Length == 0)
            {
                TraceLog.PrintLn("Not find acc()\n");
                return script;
            }

            //区分函数体内的和函数体外的声明
            //移除所有函数体
            script_tmp2 = script;
            Pattern = @"function.*?[^{]*?{[^{}]*(((?'Open'{)[^{}]*)+((?'-Open'})[^{}]*)+)*(?(Open)(?!))}";
            script_tmp2 = Regex.Replace(script, Pattern, "", RegexOptions.Singleline);
            //TraceLog.Print("script_tmp2=>{0}\n", script_tmp2);

            //记录所有全局的声明
            Pattern = @"var.*?=.*?"".*?"".*?;";
            foreach (Match var_value in Regex.Matches(script_tmp2, Pattern, RegexOptions.Multiline))
            {
                var_values = var_values + var_value.ToString();
            }

            //记录acc()
            Pattern = @"function\s*?acc[^{]*?{[^{}]*(((?'Open'{)[^{}]*)+((?'-Open'})[^{}]*)+)*(?(Open)(?!))}";
            Match acc_f = Regex.Match(script, Pattern, RegexOptions.Singleline);

            //全局声明在前,acc()在后
            script = var_values + acc_f.ToString();
            //TraceLog.Print("script=>{0}\n", script);

            accCode = ScriptHelper.runJs(script + "acc();"); //动态得到acc结果

            return accCode;
        }

        public static string runJs(string scriptText)
        {
            VsaEngine ve = VsaEngine.CreateEngine();
            return Microsoft.JScript.Eval.JScriptEvaluate(scriptText, ve).ToString();
        }
    }
}
